package com.bhprod.comatule.db;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {

// TODO The database is created in memory : uncomment to physically create it
//	private static final String DATABASE_NAME = "comatule.db";
	private static final String DATABASE_NAME = null;
	private static final int DATABASE_VERSION = 1;
	private Context context;

	public DBHelper(final Context context) {
//		super(context, DATABASE_NAME, new SQLiteCursorFactory(true), DATABASE_VERSION);
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this.context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		executeDBScriptFile("schema.sql", db);
		executeDBScriptFile("data.sql", db);
	}

	private void executeDBScriptFile(final String filename, final SQLiteDatabase db) {
		BufferedReader schemaFile;
		
		try {
			schemaFile = new BufferedReader(new InputStreamReader(
					context.getAssets().open(filename), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			Log.e(DBHelper.class.getName(), "Error while initializing database", e);
			return;
		} catch (IOException e) {
			Log.e(DBHelper.class.getName(), "Error while initializing database", e);
			return;
		}
		
		try {
		    while (schemaFile.ready()) {
		        String stmt = schemaFile.readLine();
		        db.execSQL(stmt);
		    }
		    Log.i(DBHelper.class.getName(), filename + " loaded");
		} catch (IOException e) {
			Log.e(DBHelper.class.getName(), "Error while initializing database", e);
		} finally {
			try {
				schemaFile.close();
			} catch (IOException e) {
				Log.e(DBHelper.class.getName(), "Error while initializing database", e);
			}
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}

}
